package org.example.env_boot.service;

import org.example.env_boot.dto.ApiResponse;
import org.example.env_boot.entity.AqiFeedback;
import org.example.env_boot.entity.Supervisor;
import org.example.env_boot.repository.AqiFeedbackRepository;
import org.example.env_boot.repository.SupervisorRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * 公众监督员服务类
 */
@Service
public class SupervisorService {
    
    private final AqiFeedbackRepository feedbackRepository;
    private final SupervisorRepository supervisorRepository;
    
    public SupervisorService(AqiFeedbackRepository feedbackRepository, 
                            SupervisorRepository supervisorRepository) {
        this.feedbackRepository = feedbackRepository;
        this.supervisorRepository = supervisorRepository;
    }
    
    /**
     * 提交反馈信息
     */
    public ApiResponse<AqiFeedback> submitFeedback(Integer supervisorId, Integer provinceId, Integer cityId, 
                                                   Integer aqiId, Integer so2Density, Integer coDensity, Integer spmDensity, String remarks) {
        // 验证监督员是否存在
        Optional<Supervisor> supervisorOpt = supervisorRepository.findById(supervisorId);
        if (supervisorOpt.isEmpty()) {
            return ApiResponse.error("公众监督员不存在");
        }
        
        // 验证必填字段
        if (provinceId == null || cityId == null || aqiId == null || 
            so2Density == null || coDensity == null || spmDensity == null) {
            return ApiResponse.badRequest("省份、城市、AQI级别和污染物浓度信息不能为空");
        }
        
        // 创建反馈信息
        AqiFeedback feedback = new AqiFeedback();
        feedback.setSupervisorId(supervisorId);
        feedback.setProvinceId(provinceId);
        feedback.setCityId(cityId);
        feedback.setAqiId(aqiId);
        feedback.setSo2Density(so2Density);
        feedback.setCoDensity(coDensity);
        feedback.setSpmDensity(spmDensity);
        feedback.setRemarks(remarks);
        
        // 设置反馈时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        feedback.setDateTime(now.format(dateTimeFormatter));
        
        // 设置初始状态为未指派
        feedback.setState(0);
        
        AqiFeedback savedFeedback = feedbackRepository.save(feedback);
        
        return ApiResponse.success("反馈信息提交成功", savedFeedback);
    }
    
    /**
     * 获取监督员的历史反馈信息
     */
    public ApiResponse<List<AqiFeedback>> getFeedbackHistory(Integer supervisorId) {
        // 验证监督员是否存在
        Optional<Supervisor> supervisorOpt = supervisorRepository.findById(supervisorId);
        if (supervisorOpt.isEmpty()) {
            return ApiResponse.error("公众监督员不存在");
        }
        
        List<AqiFeedback> feedbacks = feedbackRepository.findBySupervisorIdOrderByDateTimeDesc(supervisorId);
        return ApiResponse.success("获取历史反馈信息成功", feedbacks);
    }
    
    /**
     * 获取监督员的反馈统计信息
     */
    public ApiResponse<FeedbackStatistics> getFeedbackStatistics(Integer supervisorId) {
        // 验证监督员是否存在
        Optional<Supervisor> supervisorOpt = supervisorRepository.findById(supervisorId);
        if (supervisorOpt.isEmpty()) {
            return ApiResponse.error("公众监督员不存在");
        }
        
        Long totalCount = feedbackRepository.countBySupervisorId(supervisorId);
        Long pendingCount = feedbackRepository.findBySupervisorId(supervisorId).stream()
                .mapToLong(feedback -> feedback.getState() == 0 ? 1 : 0)
                .sum();
        Long assignedCount = feedbackRepository.findBySupervisorId(supervisorId).stream()
                .mapToLong(feedback -> feedback.getState() == 1 ? 1 : 0)
                .sum();
        Long confirmedCount = feedbackRepository.findBySupervisorId(supervisorId).stream()
                .mapToLong(feedback -> feedback.getState() == 2 ? 1 : 0)
                .sum();
        
        FeedbackStatistics statistics = new FeedbackStatistics();
        statistics.setTotalCount(totalCount);
        statistics.setPendingCount(pendingCount);
        statistics.setAssignedCount(assignedCount);
        statistics.setConfirmedCount(confirmedCount);
        
        return ApiResponse.success("获取反馈统计信息成功", statistics);
    }
    
    /**
     * 根据反馈ID获取详细信息
     */
    public ApiResponse<AqiFeedback> getFeedbackDetail(Integer supervisorId, Integer feedbackId) {
        Optional<AqiFeedback> feedbackOpt = feedbackRepository.findById(feedbackId);
        if (feedbackOpt.isEmpty()) {
            return ApiResponse.error("反馈信息不存在");
        }
        
        AqiFeedback feedback = feedbackOpt.get();
        if (!feedback.getSupervisorId().equals(supervisorId)) {
            return ApiResponse.forbidden("无权查看此反馈信息");
        }
        
        return ApiResponse.success("获取反馈详情成功", feedback);
    }
    
    /**
     * 反馈统计信息类
     */
    public static class FeedbackStatistics {
        private Long totalCount;      // 总反馈数
        private Long pendingCount;    // 未指派数
        private Long assignedCount;   // 已指派数
        private Long confirmedCount;  // 已确认数
        
        public Long getTotalCount() { return totalCount; }
        public void setTotalCount(Long totalCount) { this.totalCount = totalCount; }
        public Long getPendingCount() { return pendingCount; }
        public void setPendingCount(Long pendingCount) { this.pendingCount = pendingCount; }
        public Long getAssignedCount() { return assignedCount; }
        public void setAssignedCount(Long assignedCount) { this.assignedCount = assignedCount; }
        public Long getConfirmedCount() { return confirmedCount; }
        public void setConfirmedCount(Long confirmedCount) { this.confirmedCount = confirmedCount; }
    }
} 